#!/usr/bin/env bash

# Run this script to regenerate CLK_SOURCES.cmake after you add or remove any
# source files.

set -euo pipefail

script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
top_dir="$script_dir/.."

out="$script_dir/CLK_SOURCES.cmake"
trap 'rm -f "$tmp"' EXIT
tmp=$(mktemp "$out.XXXXXXXX")

awkscript='
BEGIN {
	print ind pre "CLK_SOURCES"
}

{
	if (NR > 1 && last != $1)
		print ""
	last = $1
	sub("^", ind "\t")
	print
}

END {
	print ind ")"
}
'

write_sources() {
	local ind="$1"
	local pre="$2"
	shift 2
	find -s "$@" | awk -F/ -vind="$ind" -vpre="$pre" "$awkscript" || exit $?
}

cd "$top_dir"
printf '# Generated by %s.\n\n' "${BASH_SOURCE[0]##*/}" > "$tmp"
write_sources '' 'set(' [A-Z]* -name OSBindings -prune -o \
	-name '*AllRAM*.cpp' -prune -o -name '*.cpp' -print >> "$tmp"
# TODO: Add 'Mac/Clock Signal'
# TODO: Add Qt
for dir in SDL; do
	ui=$(echo "${dir%%/*}" | tr '[:lower:]' '[:upper:]')
	dir="OSBindings/$dir"
	printf '\nif(CLK_UI STREQUAL "%s")\n' "$ui" >> "$tmp"
	if [[ $ui = "MAC" ]]; then
		args=('-name' '*.m' '-o' '-name' '*.metal' '-o' '-name' '*.mm' '-o' '-name' '*.swift')
	else
		args=('-name' '*.cpp')
	fi
	write_sources $'\t' 'list(APPEND ' "$dir" "${args[@]}" >> "$tmp"
	printf 'endif()\n' >> "$tmp"
done
mv "$tmp" "$out"
